package ai.people.core.web.filter.fastjson;

import ai.people.netmon.framework.annotation.SymbolConversion;
import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 符号转换过滤器
 *
 * @author yuanqinglong
 * @date 2022/4/29 10:17
 */
@Slf4j
public class SymbolConversionFilter implements ValueFilter {

    /**
     * 过程
     *
     * @param object 对象
     * @param name   名字
     * @param value  价值
     * @return {@link Object}
     */
    @Override
    public Object process(Object object, String name, Object value) {
        if (object instanceof Map ||ObjectUtils.isEmpty(value) || !(value instanceof String)) {
            return value;
        }
        SymbolConversion symbolConversion = object.getClass().getAnnotation(SymbolConversion.class);
        return Optional.ofNullable(symbolConversion).map(conversion -> this.convertAllProperties(object, name, value, symbolConversion))
                .orElseGet(() -> this.convertProperties( object,  name,  value));
    }

    /**
     * 将所有属性
     *
     * @param object           对象
     * @param name             名字
     * @param value            价值
     * @param symbolConversion 符号转换
     * @return {@link Object}
     */
    private Object convertAllProperties(Object object, String name, Object value, SymbolConversion symbolConversion) {
        try {
            Field field = object.getClass().getDeclaredField(name);
            if (field.getType() != String.class) {
                return value;
            }
            return ((String) value).replaceAll(symbolConversion.value(), symbolConversion.conversion());
        } catch (NoSuchFieldException e) {
            return value;
        }
    }

    /**
     * 转换属性
     *
     * @param object 对象
     * @param name   名字
     * @param value  价值
     * @return {@link Object}
     */
    private Object convertProperties(Object object, String name, Object value) {
        try {
            Field field = object.getClass().getDeclaredField(name);
            SymbolConversion conversion = field.getAnnotation(SymbolConversion.class);
            if (field.getType() == String.class && Objects.nonNull(conversion)) {
                return ((String) value).replaceAll(conversion.value(), conversion.conversion());
            }
            return value;
        } catch (NoSuchFieldException e) {
            return value;
        }
    }


}